﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Toolkits.EntityFrameworkCore.Extensions;
using SD.Toolkits.Recursion.Tree;
using SlamDunk.MES.Domain.Entities.FoundationContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.FoundationContext;
using SlamDunk.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.FoundationContext
{
    /// <summary>
    /// 工厂模型仓储实现
    /// </summary>
    public class FacilityRepository : EFAggRootRepositoryProvider<Facility>, IFacilityRepository
    {
        #region # 完整获取工厂模型 —— Facility SingleFully(Guid facilityId)
        /// <summary>
        /// 完整获取工厂模型
        /// </summary>
        /// <param name="facilityId">工厂模型Id</param>
        /// <returns>工厂模型</returns>
        public Facility SingleFully(Guid facilityId)
        {
            IQueryable<Facility> facilitys = base.Find<Facility>(x => x.Id == facilityId);
            facilitys = facilitys.IncludeNavigationProperties();
            Facility facility = facilitys.Single();

            return facility;
        }
        #endregion

        #region # 深度获取工厂模型列表 —— ICollection<Facility> FindDeeply(string keywords...
        /// <summary>
        /// 深度获取工厂模型列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="facilityLevel">工厂模型层次</param>
        /// <param name="facilityType">工厂模型类型</param>
        /// <param name="parentNodeId">上级节点Id</param>
        /// <returns>工厂模型列表</returns>
        public ICollection<Facility> FindDeeply(string keywords, FacilityLevel? facilityLevel, FacilityType? facilityType, Guid? parentNodeId)
        {
            Expression<Func<Facility, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords)) &&
                    (facilityLevel == null || x.FacilityLevel == facilityLevel) &&
                    (facilityType == null || x.FacilityType == facilityType) &&
                    (parentNodeId == null || x.ParentNode.Id == parentNodeId);

            IQueryable<Facility> facilitys = base.Find(condition);
            IEnumerable<Facility> deepFacilities = facilitys.TailRecurseParentNodes();

            return deepFacilities.ToList();
        }
        #endregion

        #region # 获取根级工厂模型列表 —— ICollection<Facility> FindRoots()
        /// <summary>
        /// 获取根级工厂模型列表
        /// </summary>
        /// <returns>工厂模型列表</returns>
        public ICollection<Facility> FindRoots()
        {
            Expression<Func<Facility, bool>> condition =
                x =>
                    x.ParentNode == null;

            IQueryable<Facility> facilitys = base.Find(condition);

            return facilitys.ToList();
        }
        #endregion
    }
}
